#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HAI优化系统主控制器
整合所有模块，提供统一的控制接口
"""

import time
import logging
import threading
from typing import Dict, Any, Optional, List
from datetime import datetime
import json

# 导入各个模块
from .user_identification import user_identifier, fair_queue
from .task_distribution import load_balancer, task_distributor, Task, TaskStatus
from .logging_system import structured_logger, log_analyzer
from .tencent_hai_api import hai_client, hai_manager
from .auto_scaling import AutoScaler
from .traffic_monitoring import initialize_traffic_monitoring
from .fault_tolerance import initialize_fault_tolerance
from .analysis_system import initialize_analysis_system
from .server_sync_manager import ServerSyncManager, ServerSyncScheduler
from .session_manager import session_manager
from .api_gateway_registry import api_gateway_registry
from config.config import CONFIG, validate_config

logger = logging.getLogger(__name__)


class HAIOptimizationController:
    """HAI优化系统主控制器"""
    
    def __init__(self):
        """初始化控制器"""
        self.running = False
        self.start_time = None
        
        # 验证配置
        config_errors = validate_config()
        if config_errors:
            logger.error(f"配置验证失败: {config_errors}")
            raise ValueError(f"配置验证失败: {config_errors}")
        
        # 初始化各个模块
        self.user_identifier = user_identifier
        self.fair_queue = fair_queue
        self.load_balancer = load_balancer
        self.task_distributor = task_distributor
        self.structured_logger = structured_logger
        self.log_analyzer = log_analyzer
        self.hai_client = hai_client
        self.hai_manager = hai_manager
        
        # 初始化自动扩缩容器
        self.auto_scaler = AutoScaler(
            self.hai_client,
            self.load_balancer,
            self.fair_queue,
            self.structured_logger
        )
        
        # 初始化流量监控和成本控制
        self.traffic_monitor, self.cost_optimizer = initialize_traffic_monitoring(
            self.structured_logger, self.hai_client, CONFIG
        )
        
        # 初始化故障转移机制
        self.health_checker, self.fault_tolerance_manager = initialize_fault_tolerance(
            self.structured_logger, self.load_balancer, self.hai_client
        )
        
        # 初始化复盘分析系统
        self.data_analyzer, self.report_generator = initialize_analysis_system(
            self.structured_logger, CONFIG['logging']['log_dir']
        )
        
        # 初始化服务器同步管理器
        self.server_sync_manager = ServerSyncManager(self.load_balancer, self.hai_client)
        self.server_sync_scheduler = ServerSyncScheduler(self.server_sync_manager)
        
        # 启动状态
        self.modules_started = {
            'hai_manager': False,
            'task_distributor': False,
            'auto_scaler': False,
            'traffic_monitor': False,
            'fault_tolerance': False,
            'server_sync': False
        }
        
        # 统计信息
        self.stats = {
            'total_tasks_processed': 0,
            'total_tasks_successful': 0,
            'total_tasks_failed': 0,
            'total_servers_created': 0,
            'total_servers_destroyed': 0,
            'total_scaling_actions': 0,
            'uptime': 0
        }
        
        logger.info("HAI优化系统控制器已初始化")
    
    def start(self) -> bool:
        """启动系统"""
        try:
            logger.info("正在启动HAI优化系统...")
            
            # 预配置应用
            if CONFIG['system']['enable_preconfiguration']:
                self._preconfigure_applications()
            
            # 启动各个模块
            self._start_modules()
            
            # 启动API网关自动注册
            self._start_api_gateway_registration()
            
            # 启动主循环
            self.running = True
            self.start_time = time.time()
            
            logger.info("HAI优化系统启动成功")
            return True
            
        except Exception as e:
            logger.error(f"HAI优化系统启动失败: {e}")
            return False
    
    def _start_api_gateway_registration(self):
        """启动API网关自动注册"""
        try:
            # 检查是否启用自动注册
            if not CONFIG['system']['enable_api_gateway_auto_registration']:
                logger.info("API网关自动注册已禁用，跳过启动")
                return
            
            # 启动自动注册（使用配置中的参数）
            api_gateway_registry.start_auto_registration()
            logger.info("API网关自动注册已启动")
        except Exception as e:
            logger.error(f"启动API网关自动注册失败: {e}")
    
    def stop(self) -> None:
        """停止系统"""
        try:
            logger.info("正在停止HAI优化系统...")
            
            self.running = False
            
            # 停止API网关自动注册
            api_gateway_registry.stop_auto_registration()
            
            # 停止各个模块
            self._stop_modules()
            
            logger.info("HAI优化系统已停止")
            
        except Exception as e:
            logger.error(f"HAI优化系统停止失败: {e}")
    
    def _preconfigure_applications(self) -> None:
        """预配置应用"""
        try:
            logger.info("开始预配置应用...")
            
            preconfig_regions = CONFIG['regions']['preconfigure_regions']
            results = self.hai_client.preconfigure_applications(preconfig_regions)
            
            success_count = sum(1 for success in results.values() if success)
            total_count = len(results)
            
            logger.info(f"预配置完成: {success_count}/{total_count} 个地域成功")
            
            # 记录预配置结果
            self.structured_logger.log_alert(
                alert_type="preconfiguration",
                severity="info",
                message="应用预配置完成",
                details={
                    "total_regions": total_count,
                    "successful_regions": success_count,
                    "results": results
                }
            )
            
        except Exception as e:
            logger.error(f"预配置应用失败: {e}")
    
    def _start_modules(self) -> None:
        """启动各个模块"""
        try:
            # 启动HAI管理器
            if not self.modules_started['hai_manager']:
                self.hai_manager.start_monitoring()
                self.modules_started['hai_manager'] = True
                logger.info("HAI管理器已启动")
            
            # 启动任务分发器
            if not self.modules_started['task_distributor']:
                self.task_distributor.start()
                self.modules_started['task_distributor'] = True
                logger.info("任务分发器已启动")
            
            # 启动自动扩缩容器
            if not self.modules_started['auto_scaler']:
                self.auto_scaler.start()
                self.modules_started['auto_scaler'] = True
                logger.info("自动扩缩容器已启动")
            
            # 启动流量监控
            if not self.modules_started['traffic_monitor']:
                self.traffic_monitor.start()
                self.modules_started['traffic_monitor'] = True
                logger.info("流量监控已启动")
            
            # 启动故障转移管理
            if not self.modules_started['fault_tolerance']:
                self.health_checker.start()
                self.fault_tolerance_manager.start()
                self.modules_started['fault_tolerance'] = True
                logger.info("故障转移管理已启动")
            
            # 启动服务器同步调度器
            if not self.modules_started['server_sync']:
                self.server_sync_scheduler.start()
                self.modules_started['server_sync'] = True
                logger.info("服务器同步调度器已启动")
                
                # 立即执行一次同步
                result = self.server_sync_manager.force_sync_now()
                if result.sync_success:
                    logger.info(f"初始同步完成: 新增{len(result.added_servers)}, 移除{len(result.removed_servers)}")
                else:
                    logger.warning(f"初始同步失败: {result.error_message}")
            
        except Exception as e:
            logger.error(f"启动模块失败: {e}")
            raise
    
    def _stop_modules(self) -> None:
        """停止各个模块"""
        try:
            # 停止自动扩缩容器
            if self.modules_started['auto_scaler']:
                self.auto_scaler.stop()
                self.modules_started['auto_scaler'] = False
                logger.info("自动扩缩容器已停止")
            
            # 停止流量监控
            if self.modules_started['traffic_monitor']:
                self.traffic_monitor.stop()
                self.modules_started['traffic_monitor'] = False
                logger.info("流量监控已停止")
            
            # 停止故障转移管理
            if self.modules_started['fault_tolerance']:
                self.health_checker.stop()
                self.fault_tolerance_manager.stop()
                self.modules_started['fault_tolerance'] = False
                logger.info("故障转移管理已停止")
            
            # 停止任务分发器
            if self.modules_started['task_distributor']:
                self.task_distributor.stop()
                self.modules_started['task_distributor'] = False
                logger.info("任务分发器已停止")
            
            # 停止HAI管理器
            if self.modules_started['hai_manager']:
                self.hai_manager.stop_monitoring()
                self.modules_started['hai_manager'] = False
                logger.info("HAI管理器已停止")
            
            # 停止服务器同步调度器
            if self.modules_started['server_sync']:
                self.server_sync_scheduler.stop()
                self.modules_started['server_sync'] = False
                logger.info("服务器同步调度器已停止")
            
        except Exception as e:
            logger.error(f"停止模块失败: {e}")
    
    def submit_task(self, task_id: str, client_ip: str, task_data: Dict[str, Any], 
                   session_id: str = None) -> Dict[str, Any]:
        """
        提交任务
        
        Args:
            task_id: 任务ID
            client_ip: 客户端IP
            task_data: 任务数据
            session_id: 会话ID（可选）
            
        Returns:
            提交结果
        """
        try:
            if not self.running:
                return {"success": False, "error": "系统未运行"}
            
            # 识别用户
            user_id = self.user_identifier.identify_user(client_ip)
            
            # 如果有会话ID，管理会话
            if session_id:
                # 创建或更新会话
                session_manager.create_session(session_id, client_ip)
                
                # 将任务添加到会话
                session_manager.add_task_to_session(session_id, task_id)
                
                logger.info(f"任务已绑定到会话: {task_id} -> {session_id}")
            
            # 添加到公平队列
            queue_user_id = self.fair_queue.add_task(task_id, client_ip, task_data)
            
            # 记录任务提交日志
            self.structured_logger.log_task_processing(
                task_id=task_id,
                user_id=user_id,
                client_ip=client_ip,
                time_window=self.user_identifier.get_time_window_id(),
                server_id="",  # 尚未分配
                region="",     # 尚未分配
                gpu_type="",   # 尚未分配
                submit_time=time.time(),
                start_time=None,
                complete_time=None,
                status="queued"
            )
            
            # 更新统计
            self.stats['total_tasks_processed'] += 1
            
            return {
                "success": True,
                "task_id": task_id,
                "user_id": user_id,
                "session_id": session_id,
                "queue_position": self.fair_queue.get_queue_status()['total_tasks_in_queue']
            }
            
        except Exception as e:
            logger.error(f"提交任务失败: {task_id}, 错误: {e}")
            return {"success": False, "error": str(e)}
    
    def cancel_session_tasks(self, session_id: str) -> Dict[str, Any]:
        """
        取消会话的所有任务
        
        Args:
            session_id: 会话ID
            
        Returns:
            取消结果
        """
        try:
            if not self.running:
                return {"success": False, "error": "系统未运行"}
            
            # 获取会话的所有任务
            tasks_to_cancel = session_manager.cancel_session_tasks(session_id)
            
            # 从队列中移除任务
            for task_id in tasks_to_cancel:
                # 这里需要实现从队列中移除任务的逻辑
                logger.info(f"任务已从队列移除: {task_id}")
            
            logger.info(f"会话任务已取消: {session_id} ({len(tasks_to_cancel)}个任务)")
            
            return {
                "success": True,
                "session_id": session_id,
                "cancelled_tasks": tasks_to_cancel,
                "task_count": len(tasks_to_cancel)
            }
            
        except Exception as e:
            logger.error(f"取消会话任务失败: {session_id}, 错误: {e}")
            return {"success": False, "error": str(e)}
    
    def get_task_status(self, task_id: str) -> Dict[str, Any]:
        """获取任务状态"""
        try:
            # 先从公平队列获取任务状态
            task_info = self.fair_queue.get_task_info(task_id)
            
            # 如果公平队列中没有，尝试从负载均衡器获取
            if not task_info:
                task_info = self._get_task_from_load_balancer(task_id)
            
            if not task_info:
                return {
                    "task_id": task_id,
                    "status": "not_found",
                    "error": "任务不存在"
                }
            
            # 计算真实进度
            progress = self._calculate_task_progress(task_info)
            
            # 估算完成时间
            estimated_completion = self._estimate_completion_time(task_info)
            
            return {
                "task_id": task_id,
                "status": task_info.get('status', 'queued'),
                "progress": progress,
                "estimated_completion": estimated_completion,
                "queue_position": task_info.get('queue_position', 0),
                "submit_time": task_info.get('submit_time'),
                "start_time": task_info.get('start_time'),
                "processing_duration": task_info.get('processing_duration', 0)
            }
        except Exception as e:
            logger.error(f"获取任务状态失败: {task_id}, 错误: {e}")
            return {"error": str(e)}
    
    def get_task_result(self, task_id: str) -> Dict[str, Any]:
        """获取任务结果 - 返回文件路径而不是URL"""
        try:
            # 从公平队列获取任务信息
            task_info = self.fair_queue.get_task_info(task_id)
            
            if not task_info:
                return {
                    "task_id": task_id,
                    "error": "任务不存在"
                }
            
            # 检查任务是否完成
            if task_info.get('status') != 'completed':
                return {
                    "task_id": task_id,
                    "status": task_info.get('status', 'queued'),
                    "error": "任务尚未完成"
                }
            
            # 返回实际的文件路径
            file_path = task_info.get('result_file_path')
            if not file_path:
                # 如果没有文件路径，尝试构造默认路径
                results_dir = os.path.join(os.path.dirname(__file__), '..', 'results')
                os.makedirs(results_dir, exist_ok=True)
                file_path = os.path.join(results_dir, f'{task_id}.jpg')
            
            return {
                "task_id": task_id,
                "file_path": file_path,
                "status": "completed",
                "processing_duration": task_info.get('processing_duration', 0),
                "complete_time": task_info.get('complete_time')
            }
        except Exception as e:
            logger.error(f"获取任务结果失败: {task_id}, 错误: {e}")
            return {"error": str(e)}
    
    def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        try:
            # 更新运行时间
            if self.start_time:
                self.stats['uptime'] = time.time() - self.start_time
            
            # 获取各模块状态
            queue_status = self.fair_queue.get_queue_status()
            system_metrics = self.load_balancer.get_system_metrics()
            hai_stats = self.hai_client.get_system_statistics()
            scaling_status = self.auto_scaler.get_scaling_status()
            
            return {
                "system": {
                    "running": self.running,
                    "uptime": self.stats['uptime'],
                    "start_time": self.start_time
                },
                "modules": self.modules_started,
                "queue": queue_status,
                "servers": system_metrics,
                "hai": hai_stats,
                "scaling": scaling_status,
                "statistics": self.stats
            }
            
        except Exception as e:
            logger.error(f"获取系统状态失败: {e}")
            return {"error": str(e)}
    
    def get_user_statistics(self) -> Dict[str, Any]:
        """获取用户统计"""
        try:
            return self.user_identifier.get_user_statistics()
        except Exception as e:
            logger.error(f"获取用户统计失败: {e}")
            return {"error": str(e)}
    
    def get_queue_status(self) -> Dict[str, Any]:
        """获取队列状态"""
        try:
            return self.fair_queue.get_queue_status()
        except Exception as e:
            logger.error(f"获取队列状态失败: {e}")
            return {"error": str(e)}
    
    def get_server_list(self, region: str = None, status: str = None) -> List[Dict[str, Any]]:
        """获取服务器列表"""
        try:
            instances = self.hai_client.list_instances(region=region, status=status)
            return [instance.to_dict() for instance in instances]
        except Exception as e:
            logger.error(f"获取服务器列表失败: {e}")
            return []
    
    def get_real_apps_status(self) -> Dict[str, Any]:
        """获取真实应用状态"""
        try:
            return self.hai_client.get_real_apps_status()
        except Exception as e:
            logger.error(f"获取真实应用状态失败: {e}")
            return {"error": str(e)}
    
    def send_task_to_app(self, app_id: str, task_data: Dict[str, Any]) -> Dict[str, Any]:
        """向指定应用发送任务"""
        try:
            return self.hai_client.send_request_to_app(app_id, "/api/v1/enhance", task_data)
        except Exception as e:
            logger.error(f"向应用发送任务失败: {e}")
            return {"error": str(e)}
    
    def get_next_available_app(self, current_app_id: str = None) -> str:
        """获取下一个可用应用"""
        try:
            return self.hai_client.get_next_available_app(current_app_id)
        except Exception as e:
            logger.error(f"获取下一个可用应用失败: {e}")
            return ""
    
    def create_server(self, region: str = None, gpu_type: str = None) -> Dict[str, Any]:
        """创建服务器"""
        try:
            instance_id = self.hai_client.create_instance(region=region, gpu_type=gpu_type)
            
            if instance_id:
                # 添加到负载均衡器
                from .task_distribution import Server
                server = Server(
                    server_id=instance_id,
                    region=region or CONFIG['tencent']['region'],
                    gpu_type=gpu_type or CONFIG['gpu_types']['default_type'],
                    status="HEALTHY",
                    created_time=time.time(),
                    endpoint=f"http://{instance_id}.hai.tencentcloud.com"
                )
                self.load_balancer.add_server(server)
                
                self.stats['total_servers_created'] += 1
                
                # 触发服务器同步
                if hasattr(self, 'server_sync_manager'):
                    self.server_sync_manager.force_sync = True
                
                return {"success": True, "instance_id": instance_id}
            else:
                return {"success": False, "error": "创建实例失败"}
                
        except Exception as e:
            logger.error(f"创建服务器失败: {e}")
            return {"success": False, "error": str(e)}
    
    def destroy_server(self, instance_id: str) -> Dict[str, Any]:
        """销毁服务器"""
        try:
            # 从负载均衡器移除
            self.load_balancer.remove_server(instance_id)
            
            # 销毁HAI实例
            success = self.hai_client.destroy_instance(instance_id)
            
            if success:
                self.stats['total_servers_destroyed'] += 1
                
                # 触发服务器同步
                if hasattr(self, 'server_sync_manager'):
                    self.server_sync_manager.force_sync = True
                
                return {"success": True}
            else:
                return {"success": False, "error": "销毁实例失败"}
                
        except Exception as e:
            logger.error(f"销毁服务器失败: {e}")
            return {"success": False, "error": str(e)}
    
    def get_daily_report(self, date: str = None) -> Dict[str, Any]:
        """获取每日报告"""
        try:
            if date is None:
                date = datetime.now().strftime('%Y-%m-%d')
            
            return self.report_generator.generate_daily_report(date)
            
        except Exception as e:
            logger.error(f"获取每日报告失败: {e}")
            return {"error": str(e)}
    
    def get_weekly_report(self, week_start_date: str = None) -> Dict[str, Any]:
        """获取每周报告"""
        try:
            if week_start_date is None:
                # 计算本周开始日期
                today = datetime.now()
                week_start = today - timedelta(days=today.weekday())
                week_start_date = week_start.strftime('%Y-%m-%d')
            
            return self.report_generator.generate_weekly_report(week_start_date)
            
        except Exception as e:
            logger.error(f"获取每周报告失败: {e}")
            return {"error": str(e)}
    
    def get_monthly_report(self, month: str = None) -> Dict[str, Any]:
        """获取每月报告"""
        try:
            if month is None:
                month = datetime.now().strftime('%Y-%m')
            
            return self.report_generator.generate_monthly_report(month)
            
        except Exception as e:
            logger.error(f"获取每月报告失败: {e}")
            return {"error": str(e)}
    
    def get_traffic_status(self) -> Dict[str, Any]:
        """获取流量状态"""
        try:
            return self.traffic_monitor.get_traffic_status()
        except Exception as e:
            logger.error(f"获取流量状态失败: {e}")
            return {"error": str(e)}
    
    def get_cost_status(self) -> Dict[str, Any]:
        """获取成本状态"""
        try:
            return self.traffic_monitor.get_cost_status()
        except Exception as e:
            logger.error(f"获取成本状态失败: {e}")
            return {"error": str(e)}
    
    def optimize_costs(self) -> Dict[str, Any]:
        """执行成本优化"""
        try:
            return self.cost_optimizer.optimize_costs()
        except Exception as e:
            logger.error(f"执行成本优化失败: {e}")
            return {"error": str(e)}
    
    def get_health_status(self) -> Dict[str, Any]:
        """获取健康状态"""
        try:
            return self.health_checker.get_health_status()
        except Exception as e:
            logger.error(f"获取健康状态失败: {e}")
            return {"error": str(e)}
    
    def get_fault_events(self, limit: int = 10) -> List[Dict[str, Any]]:
        """获取故障事件"""
        try:
            return self.health_checker.get_fault_events(limit)
        except Exception as e:
            logger.error(f"获取故障事件失败: {e}")
            return []
    
    def get_fault_tolerance_status(self) -> Dict[str, Any]:
        """获取故障转移状态"""
        try:
            return self.fault_tolerance_manager.get_fault_tolerance_status()
        except Exception as e:
            logger.error(f"获取故障转移状态失败: {e}")
            return {"error": str(e)}
    
    def resolve_fault(self, fault_id: str) -> bool:
        """解决故障"""
        try:
            return self.health_checker.resolve_fault(fault_id)
        except Exception as e:
            logger.error(f"解决故障失败: {e}")
            return False
    
    def cleanup_expired_data(self) -> Dict[str, Any]:
        """清理过期数据"""
        try:
            results = {}
            
            # 清理过期用户
            expired_users = self.user_identifier.cleanup_expired_users()
            results['expired_users'] = expired_users
            
            # 清理过期任务
            expired_tasks = self.fair_queue.cleanup_expired_tasks()
            results['expired_tasks'] = expired_tasks
            
            # 清理已完成任务
            completed_tasks = self.load_balancer.cleanup_completed_tasks()
            results['completed_tasks'] = completed_tasks
            
            # 清理旧日志
            old_logs = self.structured_logger.cleanup_old_logs()
            results['old_logs'] = old_logs
            
            logger.info(f"清理过期数据完成: {results}")
            return results
            
        except Exception as e:
            logger.error(f"清理过期数据失败: {e}")
            return {"error": str(e)}
    
    def update_config(self, section: str, key: str, value: Any) -> Dict[str, Any]:
        """更新配置"""
        try:
            from ..config.config import update_config
            update_config(section, key, value)
            
            # 记录配置更新日志
            self.structured_logger.log_alert(
                alert_type="config_update",
                severity="info",
                message="配置已更新",
                details={
                    "section": section,
                    "key": key,
                    "value": value
                }
            )
            
            return {"success": True}
            
        except Exception as e:
            logger.error(f"更新配置失败: {e}")
            return {"success": False, "error": str(e)}
    
    def get_config(self, section: str = None) -> Dict[str, Any]:
        """获取配置"""
        try:
            from ..config.config import get_config
            return get_config(section)
        except Exception as e:
            logger.error(f"获取配置失败: {e}")
            return {"error": str(e)}
    
    def _calculate_task_progress(self, task_info: Dict[str, Any]) -> float:
        """计算任务进度"""
        try:
            status = task_info.get('status', 'queued')
            
            if status == 'queued':
                return 0.0
            elif status == 'processing':
                # 根据处理时间计算进度
                start_time = task_info.get('start_time')
                if start_time:
                    processing_duration = time.time() - start_time
                    # 假设平均处理时间为30秒
                    progress = min(processing_duration / 30.0, 0.9) * 100
                    return round(progress, 1)
                else:
                    return 10.0  # 刚开始处理
            elif status == 'completed':
                return 100.0
            elif status == 'failed':
                return 0.0
            else:
                return 0.0
        except Exception as e:
            logger.error(f"计算任务进度失败: {e}")
            return 0.0
    
    def _estimate_completion_time(self, task_info: Dict[str, Any]) -> float:
        """估算任务完成时间"""
        try:
            status = task_info.get('status', 'queued')
            
            if status == 'completed':
                return task_info.get('complete_time', time.time())
            elif status == 'failed':
                return time.time()
            elif status == 'processing':
                start_time = task_info.get('start_time')
                if start_time:
                    # 假设剩余处理时间为总时间的20%
                    elapsed = time.time() - start_time
                    remaining = elapsed * 0.25  # 剩余25%时间
                    return time.time() + remaining
                else:
                    return time.time() + 30  # 默认30秒
            else:  # queued
                queue_position = task_info.get('queue_position', 0)
                # 根据队列位置估算等待时间
                wait_time = queue_position * 30  # 每个任务30秒
                return time.time() + wait_time
        except Exception as e:
            logger.error(f"估算完成时间失败: {e}")
            return time.time() + 30

    def _get_task_from_load_balancer(self, task_id: str) -> Optional[Dict[str, Any]]:
        """从负载均衡器获取任务信息"""
        try:
            task = self.load_balancer.get_task(task_id)
            if task:
                return {
                    'task_id': task.task_id,
                    'status': 'processing' if task.status.value == 'processing' else task.status.value,
                    'start_time': task.start_time,
                    'assigned_server': task.assigned_server,
                    'submit_time': task.submit_time,
                    'processing_duration': time.time() - task.start_time if task.start_time else 0
                }
            return None
        except Exception as e:
            logger.error(f"从负载均衡器获取任务失败: {task_id}, 错误: {e}")
            return None


# 全局实例
controller = HAIOptimizationController()


def get_controller() -> HAIOptimizationController:
    """获取控制器实例"""
    return controller


if __name__ == "__main__":
    # 测试代码
    logging.basicConfig(level=logging.INFO)
    
    # 创建控制器实例
    test_controller = HAIOptimizationController()
    
    # 启动系统
    if test_controller.start():
        print("HAI优化系统启动成功")
        
        # 测试提交任务
        result = test_controller.submit_task(
            task_id="test_task_001",
            client_ip="192.168.1.100",
            task_data={"image": "test.jpg", "enhancement": "upscale"}
        )
        print(f"提交任务结果: {result}")
        
        # 测试获取系统状态
        status = test_controller.get_system_status()
        print(f"系统状态: {json.dumps(status, indent=2, ensure_ascii=False)}")
        
        # 停止系统
        test_controller.stop()
        print("HAI优化系统已停止")
    else:
        print("HAI优化系统启动失败")
